package com.sy.simpleegg.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.sy.simpleegg.constant.Constant
import com.sy.simpleegg.constant.Constant.BACK_HOME_TIME
import com.sy.simpleegg.event.SwitchFragmentEvent
import com.sy.simpleegg.ext.countDown
import com.sy.simpleegg.ext.logFile
import com.sy.simpleegg.ui.fragment.config.FragmentEnum
import com.sy.simpleegg.util.Preference
import com.sy.simpleegg.util.SoftInputUtil
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.cancel
import org.greenrobot.eventbus.EventBus

abstract class BaseFragment<VB: ViewBinding>: Fragment() {

    private var _binding: VB? = null
    val binding get() = _binding!!

    private var countdownTime : Int by Preference(Constant.SETTING_BACK_HOME_TIME, BACK_HOME_TIME)

    private var timeDownScope: CoroutineScope? = null

    private var lastClickTime = 0L

    /**
     * 视图是否加载完毕
     */
    private var isViewPrepare = false

    /**
     * 数据是否加载过了
     */
    private var hasLoadData = false

    var openEventBus = false

    var isCountDownBackHome = true
    var clearShopcartEvent: (() -> Unit)? = null

    abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB

    @LayoutRes
    abstract fun attachLayoutRes(): Int

    abstract fun initView(view: View)

    abstract fun lazyLoad()

    open fun useEventBus(): Boolean = openEventBus

    override fun onResume() {
        super.onResume()
        if (isCountDownBackHome){
            startCountDown()
        }
        SoftInputUtil.hideSoftInput(binding.root)
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)

        SoftInputUtil.hideSoftInput(binding.root)

        when{
            hidden && isCountDownBackHome -> {
                cancelCountDown()
            }

            !hidden && isCountDownBackHome -> {
                startCountDown()
            }
        }
    }

    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser){
            lazyLoadDataPrepared()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = getViewBinding(inflater, container)
        return _binding?.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        if (useEventBus()){
            EventBus.getDefault().register(this)
        }
        isViewPrepare = true
        initView(view)
        lazyLoadDataPrepared()
    }

    private fun lazyLoadDataPrepared(){
        if (userVisibleHint && isViewPrepare && !hasLoadData){
            lazyLoad()
            hasLoadData = true
        }
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    override fun onDestroy() {
        super.onDestroy()
        if (useEventBus()){
            EventBus.getDefault().unregister(this)
        }
    }

    fun startCountDown(t: Int){
        timeDownScope?.cancel()
        countDown(
            time = t,
            start = {
                timeDownScope = it
                logFile("${javaClass.simpleName}开始倒计时 $t")
            },
            end = {
                logFile("${javaClass.simpleName}结束倒计时")

            },
            next = {
                if (it == 0){
                    logFile("${javaClass.simpleName}超时返回首页")
                    clearShopcartEvent?.invoke()
                    EventBus.getDefault().post(SwitchFragmentEvent(FragmentEnum.HOME))
                }
            })
    }

    fun startCountDown(){
        timeDownScope?.cancel()
        countDown(
            time = countdownTime,
            start = {
                timeDownScope = it
                logFile("${javaClass.simpleName}开始倒计时 $countdownTime")
            },
            end = {
                logFile("${javaClass.simpleName}结束倒计时")

            },
            next = {
                if (it == 0){
                    logFile("${javaClass.simpleName}超时返回首页")
                    clearShopcartEvent?.invoke()
                    EventBus.getDefault().post(SwitchFragmentEvent(FragmentEnum.HOME))
                }
            })
    }

    fun cancelCountDown(){
        timeDownScope?.cancel()
    }

    fun isFirstClick(): Boolean{
        val currentClickTime = System.currentTimeMillis()
        val canClick = currentClickTime - lastClickTime >= Constant.CLICK_INTERVAL
        lastClickTime = currentClickTime
        return canClick
    }

    fun setClearShopCart(clear: (() -> Unit)) {
        clearShopcartEvent = clear
    }
}